package com.heima.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.admin.feign.ApArticleFeign;
import com.heima.admin.feign.WmMediaFeign;
import com.heima.admin.mapper.AdSensitiveMapper;
import com.heima.admin.service.AdChannelService;
import com.heima.admin.service.ApArticleAutoHandleService;
import com.heima.common.aliyun.GreeTextScan;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.model.admin.dtos.NewsAuthDto;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.pojos.WmNews;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.media.vo.WmNewsVo;
import com.heima.utils.common.SensitiveWordUtil;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.text.StrBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class ApArticleAutoHandleServiceImpl implements ApArticleAutoHandleService {
    @Value("${fileServerUrl}")
    private String fileServerUrl;
    @Autowired
    private ApArticleFeign apArticleFeign;
    @Autowired
    private WmMediaFeign wmMediaFeign;
    @Autowired
    private AdSensitiveMapper adSensitiveMapper;
    @Autowired
    private GreeTextScan greeTextScan;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    public AdChannelService adChannelService;

    @Override
    public PageResponseResult findNews(NewsAuthDto dto) {
        //分页查询
        PageResponseResult responseResult = wmMediaFeign.findList(dto);
        //有图片需要显示，需要fasfdfs服务器地址
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public ResponseResult findOne(Integer id) {
        //1参数检查
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2查询数据
        WmNewsVo wmNewsVo = wmMediaFeign.findWmNewsVo(id);
        //结构封装
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public ResponseResult updateStatus(Integer type, NewsAuthDto dto) {
        //1.参数检查
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = wmMediaFeign.findById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.审核没有通过
        if (type.equals(0)) {
            updateWmNews(wmNews, (short) 2, dto.getMsg());
        } else if (type.equals(1)) {
            //4.人工审核通过
            updateWmNews(wmNews, (short) 4, "人工审核通过");
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 更新文章信息
     *
     * @param wmNews
     * @param i
     * @param msg
     */
    private void updateWmNews(WmNews wmNews, short i, String msg) {
        wmNews.setStatus(i);
        wmNews.setReason(msg);
        // 保存wmNews信息
        wmMediaFeign.updateNewsStatus(wmNews);
    }

    /**
     * 自动审核文章
     *
     * @param wmNewsId
     */
    @Override
    public void autoReviewrticlesA(Integer wmNewsId) {
        if (wmNewsId == null) return;
        // 通过文章id查询文章信息
        WmNews wmNews = wmMediaFeign.findById(wmNewsId);
        if (wmNews == null) return;

        // 状态为4，直接保存
        if (wmNews.getStatus() == 4) {
            // 人工审核通过
            //保存信息
            saveAppArticle(wmNews);
            return;
        }
        // 状态为8，直接保存
        if (wmNews.getStatus() == 8 && wmNews.getPublishTime().getTime() <= System.currentTimeMillis()) {
            // 已审核，待发布
            //保存信息
            saveAppArticle(wmNews);
            return;
        }
        if (wmNews.getStatus() == 1) {
            // 抽取文本和图片的信息
            Map<String, Object> contextMap = getTextAndPicInfo(wmNews);
            //  状态为1进行审核
            // 本地敏感词审核
            boolean localStatus = localSensitiveCheck(wmNews, contextMap);
            if (!localStatus) return;
            // 阿里云文本审核
            boolean aliGreenText = aliGreenTextCheck(wmNews, contextMap);
            if (!aliGreenText) return;
            // 阿里云图片审核
            boolean aliGreenImg = aliGreenImgCheck(wmNews, contextMap);
            if (!aliGreenImg) return;
            // 发布时间判断
            if (wmNews.getPublishTime().getTime() > System.currentTimeMillis()) {
                // 发布时间大于当前时间
                updateWmNews(wmNews, (short) 8, "审核通过(待发布)");
            } else {
                updateWmNews(wmNews, (short) 9, "审核通过");
            }
            //保存信息
            saveAppArticle(wmNews);
        }

    }

    /**
     * 保存文章信息
     *
     * @param wmNews
     */
    private void saveAppArticle(WmNews wmNews) {
        // 保存article信息
        ApArticle apArticle = saveArticle(wmNews);
        // 保存config信息
        saveArticleConfig(apArticle);
        // 保存conment信息
        saveArticleContent(wmNews, apArticle);

    }

    /**
     * 保存apArticlecontent信息
     *
     * @param wmNews
     * @param apArticle
     */
    private void saveArticleContent(WmNews wmNews, ApArticle apArticle) {
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        apArticleFeign.saveArticleContent(apArticleContent);
    }

    /**
     * 保存apArticle配置信息
     *
     * @param apArticle
     */
    private void saveArticleConfig(ApArticle apArticle) {
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDown(false);
        apArticleConfig.setIsForward(true);
        apArticleFeign.saveArticleConfig(apArticleConfig);
    }

    /**
     * 保存文章Article信息
     *
     * @param wmNews
     */
    private ApArticle saveArticle(WmNews wmNews) {
        ApArticle article = new ApArticle();
        article.setTitle(wmNews.getTitle());
        // 获取作者信息
        WmUser wmUserBy = wmMediaFeign.findWmUserById(wmNews.getUserId());
        if (wmUserBy != null) {
            // 通过name查询ap_author的id
            ApAuthor apAuthor = apArticleFeign.selectAuthorByName(wmUserBy.getName());
            if (apAuthor != null) {
                article.setAuthorId(apAuthor.getId().longValue());
                article.setAuthorName(apAuthor.getName());
            }

        }

        // 获取频道信息
        Integer channelId = wmNews.getChannelId();
        AdChannel channel = adChannelService.getById(channelId);
        if (channel != null) {
            article.setChannelId(channelId);
            article.setChannelName(channel.getName());
        }
        article.setImages(wmNews.getImages());
        article.setCreatedTime(wmNews.getCreatedTime());
        article.setPublishTime(wmNews.getPublishTime());

        return apArticleFeign.saveAparticle(article);

    }

    /**
     * 阿里云图片审核
     *
     * @param wmNews
     * @param contextMap
     * @return
     */
    private boolean aliGreenImgCheck(WmNews wmNews, Map<String, Object> contextMap) {
        List<String> imgs = (List<String>) contextMap.get("imgs");
        try {
            Map map = greenImageScan.imageScan(imgs);
            if (map == null) {
                return false;
            }
            String suggestion = (String) map.get("suggestion");
            if (suggestion.equals("pass")) {
                return true;
            }
            if (suggestion.equals("review")) {
                wmNews.setStatus((short) 3);
                wmNews.setReason("需人工审核");
                wmMediaFeign.updateNewsStatus(wmNews);
                return false;
            } else {
                wmNews.setStatus((short) 2);
                wmNews.setReason("审核失败");
                wmMediaFeign.updateNewsStatus(wmNews);
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 阿里云文本审核
     *
     * @param contextMap
     * @return
     */
    private boolean aliGreenTextCheck(WmNews wmNews, Map<String, Object> contextMap) {

        String text = (String) contextMap.get("text");
        try {
            Map map = greeTextScan.greeTextScan(text);
            if (map == null) {
                return false;
            }
            String suggestion = (String) map.get("suggestion");
            if (suggestion.equals("pass")) {
                return true;
            }
            if (suggestion.equals("review")) {
                wmNews.setStatus((short) 3);
                wmNews.setReason("需人工审核");
                wmMediaFeign.updateNewsStatus(wmNews);
                return false;
            } else {
                wmNews.setStatus((short) 2);
                wmNews.setReason("审核失败");
                wmMediaFeign.updateNewsStatus(wmNews);
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    /*    *//**
     * 保存文章信息
     * @param wmNews
     * @param status
     * @param msg
     *//*
    private void saveWmNews(WmNews wmNews,short status, String msg) {
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        wmMediaFeign.updateNewsStatus(wmNews);
    }*/

    /**
     * 抽取文本和图片信息
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> getTextAndPicInfo(WmNews wmNews) {
        // 把正文变成键值对
        List<Map> contextList = JSON.parseArray(wmNews.getContent(), Map.class);
        StrBuilder sb = new StrBuilder(); // 正文文本
        List<String> imgList = new ArrayList<>(); // 图片信息
        // 通过list遍历，获取对应的text和img信息
        for (Map map : contextList) {
            if ("text".equals(map.get("type"))) {
                // 文本内容
                sb.append(map.get("value"));
            }
            if ("image".equals(map.get("type"))) {
                // 文本内容
                imgList.add((String) map.get("value"));
            }
        }
        // 获取封面图片
        if (wmNews.getType() == 0 || wmNews.getImages() != null) {
            String[] split = wmNews.getImages().split(",");
            for (String s : split) {
                // 添加文件路径后放到集合中
                imgList.add(fileServerUrl + s);
            }
//            imgList.addAll(Arrays.asList(split));
        }
        // 结果map
        Map<String, Object> result = new HashMap<>();
        result.put("text", sb.toString());
        result.put("imgs", imgList);
        return result;
    }

    /**
     * 本地敏感词审核
     *
     * @param contextMap
     * @return
     */
    private boolean localSensitiveCheck(WmNews wmNews, Map<String, Object> contextMap) {
        boolean flag = true;
        // 文章中的所有文本
        String text = (String) contextMap.get("text");
        // 调用工具类审核
        boolean mark = sensitieInitAndCheck(text);
        if (!mark) {
            // 有违规
            wmNews.setStatus((short) 2);
            wmNews.setReason("本地检查包含敏感词");
            wmMediaFeign.updateNewsStatus(wmNews);
            flag = false;
        }
        return flag;
    }

    /**
     * 初始化工具类数据并进行文本审核
     *
     * @param text
     * @return T:无违规，F：有违规
     */
    private boolean sensitieInitAndCheck(String text) {
        // 从数据库查询敏感词数据
        List<String> sensitivesList = adSensitiveMapper.findAllSensitives();
        // 初始化工具类
        SensitiveWordUtil.initMap(sensitivesList);
        // 对比敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(text);
        if (map.keySet().size() == 0) {
            return true;
        } else {
            return false;
        }
    }
}
